/**
 * request 类
 * @desc 主要封装类一些ajax的方法
 * @author 张晓东
 */
import axios from 'axios';
import {Message} from "element-ui";

axios.defaults.withCredentials = true
/*
* 获取当前环境变量
* */
const {NODE_ENV} = process.env
let [baseURL, headers, timeout] = ["", {"Content-Type": "application/json;charset=UTF-8"}, 30000]
/**
 * 自动切换环境
 */

switch (NODE_ENV) {
  case "development":
    baseURL = "https://mooncake.4008123123.com/mooncake"
    break
  case "production":
    baseURL = "https://mooncake.4008123123.com/mooncake"
    break
  case "test":
    baseURL = "http://test-mooncake.daojia.com.cn"
    break
  default:
    baseUrl = "http//sss.com"
    break
}
let instance = axios.create({
  timeout, // 请求超时
  headers,
});
/**
 * 请求之前要做的事情
 */
instance.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token');
    token && (config.headers.token = token);
    config.headers.domain = window.location.host
    return config;
  },
  error => {
    return Promise.error(error);
  }
)

/**
 * 响应之后要做的事情
 */
instance.interceptors.response.use(
  response => {
    let apiUrl = response.config.url
    let message = process.env.NODE_ENV === 'development' ? `接口地址：${apiUrl}  ${response.data.msg}` : `${response.data.msg}`

    console.log(response)
    if(response.status===401){
      debugger
      window.location.href = "/admin/#/login"
    }
    if (response.data.code === 200) {
      return Promise.resolve(response.data);
    } else {
      if (response.data.code === 401) {
        window.location.href = "/admin/#/login"
      } else {
        Message({
          showClose: true,
          message,
          type: 'error'
        })
        return Promise.reject(response.data.msg)
      }
    }
  },
  error => {

    window.location.href = "/admin/#/login"

    return Promise.reject(error);
  }
);

/**
 * @class
 * @author 张晓东
 * @classdesc 一个AJAX请求对象
 * @desc 处理数据请求的类
 */
class Request {
  /**
   * axios get 请求封装
   * @author 张晓东
   * @param {*} url 接口地址
   * @param {*} params 接口参数？可选 { type:object }
   */
  static async get(url, params) {
    return await instance.get(`${baseURL}${url}`, {params})
  }

  /**
   * axios post 请求封装
   * @author 张晓东
   * @param {*} url 接口地址
   * @param {*} params 接口参数？可选 { type:object }
   */
  static async post(url, params) {
    return await instance.post(`${baseURL}${url}`, params);
  }
}

export default Request;

